# -*- coding: utf-8 -*-
"""
@Time    : 2025/2/17 10:44 
@Author  : ZhangShenao 
@File    : convert_function_to_tool.py
@Desc    : 将函数定义转换为工具调用参数
"""

import inspect
from typing import Callable, Dict, Any


def convert_function_to_tool(func: Callable) -> Dict[str, Any]:
    """将函数定义转换为工具调用参数"""
    # 获取函数签名以处理默认参数
    signature = inspect.signature(func)
    parameters = signature.parameters

    tool = {
        "type": "function",
        "function": {
            "name": func.__name__,
            "description": (func.__doc__.split('\n')[0].strip() if func.__doc__ else "") or "No description provided",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": []
            }
        }
    }

    for param_name, param in parameters.items():
        if param_name == 'return':
            continue  # 忽略返回值

        property_info = {
            "type": param.annotation.__name__ if param.annotation != inspect.Parameter.empty else "any"
        }

        tool["function"]["parameters"]["properties"][param_name] = property_info

        # 如果参数没有默认值，则认为是必填项
        if param.default == inspect.Parameter.empty:
            tool["function"]["parameters"]["required"].append(param_name)

    return tool
